import { remote } from 'electron'
import { IP } from "./ip"
import store from "electron-store"
const { BrowserWindow } = remote;
// 保持对window对象的全局引用，如果不这么做的话，当JavaScript对象被
// 垃圾回收的时候，window对象将会自动的关闭
export async function getProxy(key:string) {
	let ip = new IP(key)
	let proxy = await ip.one()
	//console.log("proxy:" + proxy)
	let config = {
		pacScript: "",
		proxyRules: proxy,
		proxyBypassRules: ""
	};

	return config
}

async function removeIP(ip: string, key:string) {
	let storage = new store()
	let pool = (<Array<string>>storage.get(key + "_pool"))
	console.log(key + "_pool", pool)
	for (var i = 0; i < pool.length; i++) {
		if (pool[i] == ip) {
			pool.splice(i, 1)
			storage.set(`${key}_pool`, pool)
		}
	}

	return true
}

export function getFaker(type:string = "computer") {
	let iphone = "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1"
	let computer = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.36 Safari/537.36"

	return type == "computer" ? {userAgent:computer} : {userAgent:iphone};
}

export async function loadUrl(win:Electron.BrowserWindow, clime:string, key:string, type:string = "computer") {
	return new Promise(async (s) => {
		let proxy = await getProxy(key)
		win.webContents.session.clearStorageData()
		win.webContents.session.setProxy(proxy, async () => {
			try {
				await win.loadURL(clime, getFaker(type))
			} catch (error) {
			}
			console.log(clime)
		})
		let isIn = await inCheck(win)
		if (isIn) {
			await removeIP(proxy.proxyRules, key)
			await loadUrl(win, clime, key, type)
		}
		s()
	});
}

export async function inCheck(win:Electron.BrowserWindow) {
	return await win.webContents.executeJavaScript(getNowAddress.toString() + ";getNowAddress();")
}

function getNowAddress() {
	return  document.title == "验证中心" ||
			document.title == "" ||
			document.body.innerText == "" ||
			document.body.innerText.includes("抱歉！页面无法访问....") ||
			document.body.innerText.includes("proxy ip has expired")
}

export async function createWindow(clime:string, key:string, type:string = "computer") {
	let loadFaker = getFaker(type)

	let config = await getProxy(key)

    // 创建浏览器窗口。
	let win = new BrowserWindow({
		width: 800,
		height: 600,
		// show: false,
		webPreferences: {
			nodeIntegration: true,
			sandbox: true,
			images: false
		}
	})

	win.webContents.session.clearStorageData()
	// let filter = {urls:["*://www.dianping.com/*"]}
	// win.webContents.session.webRequest.onBeforeSendHeaders(filter, (details, callback)=>{})
	//win.loadURL(clime, loadFaker)
	if (clime != "") {
		await win.webContents.session.setProxy( config, function () {
			win.loadURL(clime, loadFaker)
			//console.log("load complete..")
		})
	}
	// 加载index.html文件


	// 打开开发者工具
	win.webContents.openDevTools()
	//  a = await window.webContents.executeJavaScript(js, false);

	// 当 window 被关闭，这个事件会被触发。
	win.on('closed', () => {
		// 取消引用 window 对象，如果你的应用支持多窗口的话，
		// 通常会把多个 window 对象存放在一个数组里面，
		// 与此同时，你应该删除相应的元素。
	})

	return win
}
